<script setup>
	import { ref, onMounted } from 'vue'
	import taskApi from '@/apis/task.js'

	// 1. 定义响应式数据
	const pickUpList = ref([])
	const nextPage = ref(1) // 下一页
	const pages = ref(2) // 总页数
	const isTriggered = ref(false) // 默认是未触发

	// 2. 定义方法操作响应式数据
	async function getPickUpList(page = 1, pageSize = 5) {
		// 获取服务器数据
		let { data } = await taskApi.list(1, page, pageSize)
		// 赋值给响应式变量
		// 下拉刷新：将第一页数据覆盖 pickUpList.value
		if (page === 1) pickUpList.value = []
		// 上拉分页时：将新页的数据追加到前面数据中
		pickUpList.value = [...pickUpList.value, ...data.items]

		nextPage.value = ++data.page // 拿到下一页
		pages.value = data.pages // 总页数
	}

	onMounted(() => {
		// 页面加载后就发请求获取数据
		getPickUpList()
	})

	// 定义上拉分页的触底函数
	function onScrollToLower() {
		// uni.utils.toast('触底触发')
		// 1. 判断，如果 nextPage.value大于pages.value则直接不执行代码
		if (nextPage.value > pages.value) {
			return uni.utils.toast('已没有数据')
		}
		// 2. 重新调用  getPickUpList方法
		getPickUpList(nextPage.value)
	}

	// 定义下拉刷新的回调函数
	async function onRefresher() {
		// 1. 打开下拉刷新的动画图
		isTriggered.value = true
		// 2. 请求第一页数据
		const cpage = 1
		await getPickUpList(cpage)
		// 3. 关闭下拉刷新的动画图
		isTriggered.value = false
	}
</script>

<template>
	<scroll-view
		scroll-y
		refresher-enabled
		:refresher-triggered="isTriggered"
		@scrolltolower="onScrollToLower"
		@refresherrefresh="onRefresher"
		class="scroll-view"
	>
		<view class="scroll-view-wrapper">
			<view v-for="pickUp in pickUpList" :key="pickUp.id" class="task-card">
				<navigator
					hover-class="none"
					:url="`/subpkg_task/detail/index?id=${pickUp.id}`"
				>
					<view class="header">
						<text class="no">任务编号: {{ pickUp.transportTaskId }}</text>
						<text class="status">已延迟</text>
					</view>
					<view class="body">
						<view class="timeline">
							<view class="line">{{ pickUp.startAddress }}</view>
							<view class="line">{{ pickUp.endAddress }}</view>
						</view>
					</view>
				</navigator>
				<view class="footer">
					<view class="label">提货时间</view>
					<view class="time">{{ pickUp.planDepartureTime }}</view>
					<navigator
						v-if="pickUp.enablePickUp"
						hover-class="none"
						:url="`/subpkg_task/pickup/index?id=${pickUp.id}`"
						class="action"
						>提货</navigator
					>
					<button
						v-if="!pickUp.enablePickUp"
						disabled="true"
						class="action"
						style="color: #ffffff"
					>
						提货
					</button>
				</view>
			</view>
			<view v-if="false" class="task-blank">无待提货物</view>
		</view>
	</scroll-view>
</template>

<style lang="scss" scoped>
	@import './styles.scss';
</style>
